var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
var app = getApp()
var that, pollingPayResult, pollingIndex

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderResult: null, //订单结果数据
    payStatus: null, //5，待确认 6,服务器支付成功 7,服务器支付失败

    statusText:"正在确认...", //支付状态文字，默认待确认
    statusImg: "/resources/image/order_status_going.png" //支付状态图片，默认待确认
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    try {
      var orderResult = JSON.parse(decodeURIComponent(options.orderResult));
      this.setData({
        orderResult: orderResult
      })
      that.toPayStatus(5);
      that.polling();
    } catch (e) {
      console.log(e)
    }
  },

  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {
    clearInterval(pollingPayResult); //页面卸载，清除轮询
  },
  
  // 更改支付状态
  toPayStatus(res){
    that.setData({
      payStatus: res
    })
    if (res == 5){
      that.setData({
        statusText: "正在确认...",
        statusImg: "/resources/image/order_status_going.png"
      })
    } else if (res == 6) {
      that.setData({
        statusText: "付款成功",
        statusImg: "/resources/image/order_status_success.png"
      })
    } else if (res == 7) {
      that.setData({
        statusText: "确认失败",
        statusImg: "/resources/image/order_status_fail.png"
      })
    }
  },

  // 开启轮询
  polling(){
    pollingIndex=0;
    setTimeout(()=>{
      that.requestOrderPay();
      pollingPayResult = setInterval(()=>{
        if(pollingIndex<20){
          that.requestOrderPay();
        } else { //已轮询20次，停止轮询
          clearInterval(pollingPayResult);
          that.toPayStatus(7);
        }
        pollingIndex++;
      },3000);
    },2000);
  },

  // 查询订单支付结果
  requestOrderPay() {
    httpUtil.PostRequest("request_order_pay_result", {
      orderId: that.data.orderResult.orderId
    }, {
        success(res) {
          if (res.status == "success"){ //支付成功，跳转订单详情页面
            app.orderSaveMoneyInfo(that.data.orderResult.orderId,function(e){
              that.setData({
                orderSaveMoneyInfo: e.text
              })
            });
            clearInterval(pollingPayResult);
            that.toPayStatus(6);
            that.getStorageOrder(that.data.orderResult.orderId);
          } else if (res.status == "fail"){ //支付失败
            clearInterval(pollingPayResult);
            that.toPayStatus(7);
          }
        },
        fail(code, res) {
          console.log(code, res)//
        },
        complete() { }
      })
  },

  // 更改我的订单付款成功
  getStorageOrder(orderId){
    var pages = getCurrentPages();
    var lastPage = pages[pages.length - 2];
    if(lastPage.route=="pages/order/my-order/my-order"){
      lastPage.havePaidOrders(orderId);
    }
  }
})
